package com.robusta.cityuate.services;

import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ByteArrayEntity;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.robusta.cityuate.objects.Reservation;
import com.robusta.cityuate.objects.TimeSlot;
import com.robusta.cityuate.utils.ConnectionUtils;

public class ReservationService extends HTTPService {

	private static final String RERSERVATION_URL = "/reservations" ;
	private static final String OFFERINGS_URL = "/offerings/";
	private static final String SPOTS_URL = "/spots/";
	private static final String TAG = ReservationService.class.getName();
	private Context mContext = this;
	private TimeSlot slot;
	

	@Override
	protected void onResponse() {
		Intent reservationUIupdate = new Intent(assignedFilter);
		switch (responseStatusCode) {
		case HttpStatus.SC_CREATED: {
			// remove connection from shared pref
			ConnectionUtils.setDisconnecting(mContext, true, assignedFilter,
					null);
			// update UI if active
			reservationUIupdate.putExtra(RESUlT, true);
			sendOrderedBroadcast(reservationUIupdate, null);
			return;
		}
		case HttpStatus.SC_UNPROCESSABLE_ENTITY:
			
			JSONObject responseMsg;
			String msgS = "";
			try {
				responseMsg = new JSONObject(responseString);
				for (@SuppressWarnings("unchecked")
				Iterator<String> iterator = responseMsg.keys(); iterator
						.hasNext();) {
					String key = (String) iterator.next();
					msgS +=(key+" "+ responseMsg.getString(key) + "\n");
				}
			}
			catch (Exception e) {
			}
			onNoResponse(msgS);
			
			break;
		case HttpStatus.SC_NOT_FOUND:
		case HttpStatus.SC_UNAUTHORIZED:
			JSONObject msg;
			try {
				msg = new JSONObject(responseString);
				onNoResponse(msg.getString(HTTPService.MESSAGE));
			} catch (JSONException e) {
				onNoResponse(UNKNOWN_RESPONSE);
			}
		}
	}

	@Override
	protected void onNoResponse(String msg) {
		// remove connection from shared pref keeping result and reason
		ConnectionUtils.setDisconnecting(mContext, false, assignedFilter, msg);
		// update UI if active
		Intent reportSpotUIupdate = new Intent(assignedFilter);
		reportSpotUIupdate.putExtra(RESUlT, false);
		sendOrderedBroadcast(reportSpotUIupdate, null);

	}

	@Override
	protected HttpRequestBase initRequest() {
		 slot=(TimeSlot)extras.getSerializable(TimeSlot.TIME_SLOT); 
		extras.remove(TimeSlot.TIME_SLOT);
		HttpPost req=new HttpPost(HTTPService.API_URL+SPOTS_URL+slot.getOffer().getSpot().getId()+OFFERINGS_URL+slot.getOffer().getId()+RERSERVATION_URL);
		try {
			req.setEntity(createPostBody());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return req;
	}
	
	private HttpEntity createPostBody() throws UnsupportedEncodingException {
		// Creating Body
		JSONObject bodyData = new JSONObject();
		JSONObject reservation = new JSONObject();
		try {
			if (extras != null) {

				Set<String> extrasKeys = extras.keySet();
				if (!extrasKeys.isEmpty()) {

					for (String key : extrasKeys)
						try {
							bodyData.put(key, extras.get(key).toString());
						} catch (JSONException e) {
							e.printStackTrace();
						}
				}
			}
			
			reservation.put(Reservation.RESERVATION, bodyData);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		Log.e(TAG, reservation.toString());
		return new ByteArrayEntity(reservation.toString().getBytes("UTF-8"));

	}
	

}
